<template>
	<view style="position: sticky;
top: 0;
z-index: 999;">
		<uni-search-bar @confirm="gotoList(kw)" v-model="kw" @input="input(e)" cancelButton="none" clearButton="always"
			:placeholder="placeholder" :focus="true" @clear="gotoList(kw)">
			<template v-slot:clearIcon>
				<view style="color: #FFF">搜索</view>
			</template>
		</uni-search-bar>
	</view>
	<view class="px-1 bg-white" v-if="searchResults.length!==0">
		<view class="flex align-center justify-between font py-1  border-bottom" @click="gotoDetail(item.goods_id)"
			v-for="(item,index) in searchResults" :key="index">
			<view class="text-ellipsis mr-1">{{item.goods_name}}</view>
			<uni-icons type="arrowright" size="26" color="#bbb"></uni-icons>
		</view>
	</view>

	<view class="p-1 bg-white mt-1" v-else>
		<view class="flex justify-between align-center font border-bottom" style="height: 40px;">
			<text>搜索历史</text>
			<uni-icons type="trash" size="17" @click="clearHistory"></uni-icons>
		</view>
		<view class="flex flex-wrap">
			<uni-tag @click="gotoList(item)" class="mt-1 ml-1" :text="item" :key="i" v-for="(item,i) in historyList"
				:inverted="true"></uni-tag>
		</view>
	</view>
</template>

<script setup>
	import {
		onLoad
	} from "@dcloudio/uni-app"
	import {
		ref
	} from "vue"

	const historyList = ref([])
	const searchResults = ref([])
	const kw = ref('')
	const timer = ref()

	const props = defineProps({
		placeholder: String,
	})

	// const placeholder = ref('')
	onLoad(() => {
		// placeholder.value = e.placeholder
		historyList.value = JSON.parse(uni.getStorageSync('historyList') || '[]')
	})

	const input = () => {
		clearTimeout(timer.value)
		timer.value = setTimeout(() => {
			getSearchList()
		}, 500)
	}

	const saveSearchHistory = (value) => {
		historyList.value.unshift(value)
		historyList.value = [...new Set(historyList.value)]
		uni.setStorageSync('historyList', JSON.stringify(historyList.value))
	}

	const gotoDetail = (goods_id) => {
		uni.navigateTo({
			url: "/subpkg/goods_detail/goods_detail?goods_id=" + goods_id
		})
	}

	const gotoList = (item) => {
		console.log(item, typeof(item));

		if (item === '') {
			console.log("item")
			item = kw.value === '' ? props.placeholder : kw.value
		}
		uni.navigateTo({
			url: "/subpkg/goods_list/goods_list?query=" + item
		})
	}

	const getSearchList = async () => {
		if (kw.value === '') {
			searchResults.value = []
			return
		}
		const {
			data: {
				message
			}
		} = await uni.request({
			url: "https://api-hmugo-web.itheima.net/api/public/v1/goods/qsearch",
			method: "GET",
			data: {
				query: kw.value
			}
		})
		saveSearchHistory(kw.value)
		searchResults.value = message.slice(0, 6)
	}

	const clearHistory = () => {
		historyList.value = []
		uni.removeStorageSync('historyList')
	}
</script>

<style>

</style>